<?php

namespace App\Http\Controllers\Admin;

use App\models\AdminModule;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Spatie\Permission\Models\Role;

class RoleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $roles = Role::get();
        return view('admin.role_index',compact('roles'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.role_create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
//        Role::create($request->all());
//        dd($request->all());
        $data = $request->all();
        $data['guard_name'] = 'admin';
        Role::create($data);
        return redirect(route('admin.role.index'))->with('success','角色添加成功');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Role $role)
    {
        return view('admin.role_edit',compact('role'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Role $role)
    {
        $role->update($request->all());
        return redirect(route('admin.role.index'))->with('success','角色编辑成功');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Role $role)
    {
        if ($role['system']==0)
        {
            $role->delete();
        }
        return redirect(route('admin.role.index'))->with('success','角色删除成功');
    }
//    给角色分配权限
    public function permission(Role $role)
    {
        $modules = AdminModule::get();
        return view('admin.role_permission',compact('role','modules'));
    }
    public function permissionUpdate(Request $request,Role $role)
    {
//        dd($role);
//        dd($request->input('permissions'));
//        将多个权限同步到一个角色
        $role->syncPermissions($request->input('permissions'));
        return redirect(route('admin.role.index'))->with('success',"角色[{{$role['title']}}]的权限修改成功");
    }
}
